#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import uuid


# Create your views here.
@csrf_exempt
def upload_image(request):
    if request.method == "POST":
        file_obj = request.FILES['file']
        file_name_suffix = file_obj.name.split(".")[-1]
        if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]:
            return JsonResponse({"message": "错误的文件格式"})

        path = settings.TINYMCE_UPLOAD_PATH
        # 如果没有这个路径则创建
        if not os.path.exists(path):
            os.makedirs(path)

        new_name = str(uuid.uuid1()) + '.' + file_name_suffix
        file_path = os.path.join(path, new_name)

        file_url = f'{new_name}'

        with open(file_path, 'wb+') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

        return JsonResponse({
            'message': '上传图片成功',
            'location': file_url
        })
    return JsonResponse({'detail': "错误的请求"})

